package com.cc.controller;

import com.cc.entity.Employee;
import com.cc.entity.R;
import com.cc.enums.HttpEnum;
import com.cc.service.EmployeeService;
import com.cc.util.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
@CrossOrigin // 解决跨域问题
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    //获取所有员工
    @GetMapping
    public List<Employee> getAllEmployee(){
        return employeeService.getAllEmployee();
    }

    //分页
    @GetMapping("/page")
    public R<PageInfo<Employee>> getEmployeeByPage(Integer pageNum){
        PageInfo<Employee> pageUsers = employeeService.getEmployeeByPage(pageNum);
        return R.success(pageUsers);
    }


    //添加员工信息
    @PostMapping
    public R addEmployee(@Valid Employee employee, MultipartFile userImageFile, HttpServletRequest request){
        //todo 默认设置数据类型为1
        employee.setEmployeeId(1);
        //得到上传图片的地址
        String imgPath;

        try {
            //ImageUtil为之前添加的工具类
            imgPath = FileUtil.upload(request,userImageFile);
            if(imgPath != null){
                employee.setImagePath(imgPath);
                System.out.println("---------图片上传成功!");
            }else {
                System.out.println("---------图片上传失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("---------图片上传失败!");
        }
        int count = employeeService.addEmployee(employee);

        return count > 0 ? R.success("新增失败") : R.fail(HttpEnum.SUCCESS.getCode(), "新增失败");

    }
}
